package com.bnlr.lrparking.appui.carplace;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.constant.LrConstant;
import com.google.gson.Gson;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.event.PaySucceeEvent;
import com.bnlr.lrparking.model.AddCarPlaceBean;
import com.bnlr.lrparking.model.AddStallTypeBean;
import com.bnlr.lrparking.model.JsonBean;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.GetJsonDataUtil;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by hp on 2017/8/24.
 * 添加车位
 */

public class AddStallActivity extends BaseActivity {

    private TextView tvNavTitle,ed_stall_type;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private EditText selectCity,addstall_name,addstall_number,addstall_phone,addstall_price,et_add_description;//输入框
    private TextView tv_addstall_btn;
    private OptionsPickerView pvCustomOptions,pvOptions;
    private ArrayList<ArrayList<String>> carType2 = new ArrayList<>();
    private ArrayList<String> carType1 = new ArrayList<>();
    private String strselectCity,strTallName,strtallNumber,strallPhone,strstallPrice;
    private int selectId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addstall);
        getCarPlaceType();
        initView();
    }

    private void getCarPlaceType() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "GetSpaceType");
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<AddStallTypeBean>(baseContext, true, AddStallTypeBean.class) {
                        @Override
                        public void doWork(AddStallTypeBean data, String code) {
                            if (code.equals("1")) {
                                for (int i = 0; i < data.getData().size(); i++) {
                                    carType1.add(data.getData().get(i).getValue());
                                    ArrayList<String> type1 = new ArrayList<>();
                                    for (int j = 0; j < data.getData().get(i).getData().size(); j++) {
                                       type1.add(data.getData().get(i).getData().get(j).getValue());
                                    }
                                    carType2.add(type1);
                                }
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (!code.equals("1")) {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    private void initView() {
        EventBus.getDefault().register(this);//
        tvNavTitle = (TextView) findViewById(R.id.tv_nav_title);
        tvNavTitle.setText("添加车位");
        selectCity=(EditText)findViewById(R.id.ed_selectcity);
        addstall_name=(EditText)findViewById(R.id.addstall_name);
        addstall_number=(EditText)findViewById(R.id.addstall_number);
        addstall_phone=(EditText)findViewById(R.id.addstall_phone);
        addstall_price=(EditText)findViewById(R.id.addstall_price);
        et_add_description = (EditText) findViewById(R.id.et_add_description);
        ed_stall_type=(TextView) findViewById(R.id.ed_stall_type);
        tv_addstall_btn=(TextView)findViewById(R.id.tv_addstall_btn);
        tv_addstall_btn.setOnClickListener(this);
        selectCity.setOnClickListener(this);
        ed_stall_type.setOnClickListener(this);
        selectCity.addTextChangedListener(this);
        addstall_name.addTextChangedListener(this);
        addstall_number.addTextChangedListener(this);
        addstall_phone.addTextChangedListener(this);
        addstall_price.addTextChangedListener(this);
        initJsonData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySuccessEvent(PaySucceeEvent event) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void afterTextChanged(Editable s) {
        super.afterTextChanged(s);
        strselectCity=selectCity.getText().toString();
        strTallName=addstall_name.getText().toString();
        strtallNumber=addstall_number.getText().toString();
        strallPhone=addstall_phone.getText().toString();
        strstallPrice=addstall_price.getText().toString();
        final String type = ed_stall_type.getText().toString();
        if (!strselectCity.equals("")&&!strTallName.equals("")&&!strtallNumber.equals("")
                &&!strallPhone.equals("")&&!strstallPrice.equals("")&&!type.equals("")){
            tv_addstall_btn.setBackgroundResource(R.drawable.seletor_login_btn);
            tv_addstall_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!RegexUtils.isMobileExact(strallPhone)) {
                        ToastUtils.showShort("手机格式不正确");
                        return;
                    }
                    AddCarPlaceBean bean = new AddCarPlaceBean();
                    bean.setAddress(strselectCity);
                    bean.setPlaceName(strTallName);
                    bean.setPlaceNum(strtallNumber);
                    bean.setPhone(strallPhone);
                    bean.setPrice(strstallPrice);
                    bean.setCarType(type);
                    bean.setAddressId(selectId);
                    if (!TextUtils.isEmpty(et_add_description.getText().toString())) {
                        bean.setDescription(et_add_description.getText().toString());
                    }
                    startActivity(new Intent(AddStallActivity.this,SelectPhotoActivity.class)
                    .putExtra("submit_info",bean));
                }
            });
        }else {
            tv_addstall_btn.setBackgroundResource(R.mipmap.login_disabled);
            tv_addstall_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonUtil.showToask(baseContext,"请把信息填写完整！");
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ed_selectcity:
                ShowPickerView();
                break;
            case R.id.ed_stall_type:
                if (carType1.size() == 0) {
                    ToastUtils.showShort("未获取到数据");
                    return;
                }
                initCustomOptionPicker();
                break;
        }
    }


    private void ShowPickerView() {// 弹出选择器

        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()+
                        options2Items.get(options1).get(options2)+
                        options3Items.get(options1).get(options2).get(options3);
                selectCity.setText(tx);
                if ( options1Items.get(options1).getCities().size() == 0) {
                    selectId = options1Items.get(options1).getId();
                }else {
                    selectId = options1Items.get(options1).getCities().get(options2).getAreas().get(options3).getId();
                }

            }
        }).setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setSubCalSize(15)//确定和取消文字大小
                .setTitleSize(18)//标题文字大小
                .setDividerColor(getResources().getColor(R.color.gray03_color))//设置分割线的颜色
                .setTitleColor(getResources().getColor(R.color.main_color))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main_color))//取消按钮文字颜色
                .setContentTextSize(18)
                .build();
        pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器
        pvOptions.show();

    }

    private void initJsonData() {//解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this,"province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i=0;i<jsonBean.size();i++){//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            if (jsonBean.get(i).getCities()== null || jsonBean.get(i).getCities().size()==0){
                CityList.add("");
                ArrayList<String> areaList = new ArrayList<>();
                areaList.add("");
                Province_AreaList.add(areaList);
            } else {
                for (int c=0; c<jsonBean.get(i).getCities().size(); c++){//遍历该省份的所有城市
                    String CityName = jsonBean.get(i).getCities().get(c).getName();
                    CityList.add(CityName);//添加城市
                    ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                    //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                    if (jsonBean.get(i).getCities().get(c).getAreas() == null
                            ||jsonBean.get(i).getCities().get(c).getAreas().size()==0) {
                        City_AreaList.add("");
                    }else {
                        for (int d=0; d < jsonBean.get(i).getCities().get(c).getAreas().size(); d++) {//该城市对应地区所有数据
                            String AreaName = jsonBean.get(i).getCities().get(c).getAreas().get(d).getName();
                            City_AreaList.add(AreaName);//添加该城市所有地区数据
                        }
                    }
                    Province_AreaList.add(City_AreaList);//添加该省所有地区数据
                }
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);
            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    private void initCustomOptionPicker() {
        pvCustomOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = carType1.get(options1).toString()+"-"+carType2.get(options1).get(option2).toString() ;
                ed_stall_type.setText(tx);
            }
        }).setLayoutRes(R.layout.pickerview_time, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });
            }
        }).isDialog(false).build();
        pvCustomOptions.setPicker(carType1,carType2);//添加数据
        pvCustomOptions.show();
    }
}
